package com.ruoyi.admin.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.admin.domain.DailyData;
import com.ruoyi.admin.domain.NameDataPanel;
import com.ruoyi.admin.mapper.NameDataPanelMapper;
import com.ruoyi.admin.service.INameDataPanelService;


/**
 * 仪表盘服务实现类
 */
@Service
public class NameDataPanelImpl implements INameDataPanelService {
    @Autowired
    private NameDataPanelMapper nameDataPanelMapper;
    
    @Autowired
// 由于 IAlipayUserService 无法解析，暂时移除该声明
// private IAlipayUserService alipayUserService;

    @Override
    public NameDataPanel getDashboardStats() {
        // 获取当前登录用户ID
        String userId = getCurrentUserId();
        
        LocalDateTime now = LocalDateTime.now();

        // 今日 00:00:00
        LocalDateTime today = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
        // 明天 00:00:00
        LocalDateTime tomorrow = today.plusDays(1);
        // 昨天 00:00:00
        LocalDateTime yesterday = today.minusDays(1);

        // 本月第一天
        LocalDateTime firstDayOfMonth = today.withDayOfMonth(1);
        // 下月第一天
        LocalDateTime firstDayNextMonth = firstDayOfMonth.plusMonths(1);

        // 上月第一天
        LocalDateTime firstDayLastMonth = firstDayOfMonth.minusMonths(1);

        // 本年第一天
        LocalDateTime firstDayOfYear = today.withDayOfYear(1);
        // 明年第一天
        LocalDateTime firstDayNextYear = firstDayOfYear.plusYears(1);

        NameDataPanel stats = nameDataPanelMapper.selectDashboardStats(
            today, tomorrow, yesterday,
            firstDayOfMonth, firstDayNextMonth,
            firstDayLastMonth,
            firstDayOfYear, firstDayNextYear
        );

        if (stats == null) {
            stats = new NameDataPanel();
        }

        // 设置默认值防止 null
        stats.setDefaultValues();

        // 计算账户余额：假设为所有未提现收益的总和
        BigDecimal totalEarnings = stats.getYearEarnings();
        stats.setBalance(totalEarnings != null ? totalEarnings : BigDecimal.ZERO);

        // 计算可提现金额：根据规则，每月25号之后可提现上个月的收益，且未提现金额一直累加
        BigDecimal withdrawableAmount = calculateWithdrawableAmount(userId, now);
        stats.setWithdrawable(withdrawableAmount);

        return stats;
    }

    @Override
    public List<DailyData> getLastThirtyDaysData() {
        LocalDateTime now = LocalDateTime.now();
        // 获取30天前的同一时间
        LocalDateTime thirtyDaysAgo = now.minus(30, ChronoUnit.DAYS);

        List<DailyData> dailyDataList = nameDataPanelMapper.selectLastThirtyDaysData(thirtyDaysAgo);

        // 设置默认值防止null
        for (DailyData dailyData : dailyDataList) {
            dailyData.setDefaultValues();
        }

        return dailyDataList;
    }

    // 添加辅助方法来获取指定月份的收益
    private BigDecimal getMonthEarnings(int year, int month) {
        // 这里需要根据实际的数据结构来实现
        // 实际实现可能需要查询数据库或者使用其他方式获取
        // 这里返回0作为示例
        return BigDecimal.ZERO;
    }

    // 添加辅助方法来获取指定年份的收益
    private BigDecimal getYearEarnings(int year) {
        // 这里需要根据实际的数据结构来实现
        // 实际实现可能需要查询数据库或者使用其他方式获取
        // 这里返回0作为示例
        return BigDecimal.ZERO;
    }

    // 计算可提现金额
    private BigDecimal calculateWithdrawableAmount(String userId, LocalDateTime now) {
        // 初始化可提现金额为0
        BigDecimal withdrawableAmount = BigDecimal.ZERO;
        int dayOfMonth = now.getDayOfMonth();
        
        // 获取当前月份和年份
        int currentMonth = now.getMonthValue();
        int currentYear = now.getYear();
        
        // 获取已提现的总金额
        BigDecimal withdrawnAmount = nameDataPanelMapper.selectWithdrawnAmount(userId);
        if (withdrawnAmount == null) {
            withdrawnAmount = BigDecimal.ZERO;
        }
        
        // 如果今天是25号或之后，计算所有已结算但未提现的收益
        if (dayOfMonth >= 25) {
            // 计算从最早可提现日期到上月的所有收益总和
            // 获取最早的订单日期作为计算起点
            LocalDateTime earliestOrderDate = getEarliestOrderDate(userId);
            if (earliestOrderDate == null) {
                // 如果没有订单记录，返回0
                return BigDecimal.ZERO;
            }
            
            // 计算从最早订单日期到上月末的所有收益
            LocalDateTime endOfLastMonth = now.withDayOfMonth(1).minusDays(1);
            endOfLastMonth = endOfLastMonth.withHour(23).withMinute(59).withSecond(59);
            
            BigDecimal totalEligibleEarnings = nameDataPanelMapper.selectEarningsBetween(userId, earliestOrderDate, endOfLastMonth);
            if (totalEligibleEarnings == null) {
                totalEligibleEarnings = BigDecimal.ZERO;
            }
            
            // 可提现金额 = 符合条件的总收益 - 已提现金额
            withdrawableAmount = totalEligibleEarnings.subtract(withdrawnAmount);
            
            // 确保可提现金额不为负数
            if (withdrawableAmount.compareTo(BigDecimal.ZERO) < 0) {
                withdrawableAmount = BigDecimal.ZERO;
            }
        }
        
        return withdrawableAmount;
    }
    
    // 获取最早的订单日期
    private LocalDateTime getEarliestOrderDate(String userId) {
        // 在实际实现中，这里应该查询用户最早的订单日期
        // 这里仅作为示例，实际需要根据数据库结构实现
        return null;
    }
    
    // 获取当前登录用户ID
    private String getCurrentUserId() {
        // 在实际实现中，这里应该从会话或上下文中获取当前登录用户的ID
        // 这里仅作为示例，返回一个默认值
        return "default_user_id";
    }
    
    // 修改辅助方法来获取指定月份的收益
    private BigDecimal getMonthEarnings(String userId, int year, int month) {
        BigDecimal earnings = nameDataPanelMapper.selectMonthEarnings(userId, year, month);
        return earnings != null ? earnings : BigDecimal.ZERO;
    }

    // 修改辅助方法来获取指定年份的收益
    private BigDecimal getYearEarnings(String userId, int year) {
        BigDecimal earnings = nameDataPanelMapper.selectYearEarnings(userId, year);
        return earnings != null ? earnings : BigDecimal.ZERO;
    }
}
